/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package east2west.action;
import east2west.dto.CarCancelDTO;
import east2west.dto.CarOrderDTO;
import east2west.dto.CarOrderDetailDTO;
import east2west.dto.CarsDTO;
import east2west.dto.CustomerDTO;
import east2west.dto.JobDTO;
import east2west.service.CarCancelService;
import east2west.service.CarOrderDetailService;
import east2west.service.CarOrderService;
import east2west.service.CarService;
import east2west.service.CustomerService;
import east2west.service.JobService;
import east2west.util.DateTimeUtil;
import java.util.ArrayList;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;

/**
 *
 * @author anhtuan
 */
public class CarOrderAction extends DispatchAction {

    /* forward name="success" path="" */
    private final static String SUCCESS = "success";
    private final static String TRUE = "true";
    private final static String ERR = "err";

   
    public ActionForward create(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        HttpSession session = request.getSession();

        int id = Integer.parseInt(request.getParameter("carId"));
        CarService carSer = new CarService();

        ArrayList<CarOrderDetailDTO> cart = (ArrayList<CarOrderDetailDTO>) session.getAttribute("cartCar");
        if (cart == null) {
//add new cart
            cart = new ArrayList<CarOrderDetailDTO>();
            CarOrderDetailDTO detail = new CarOrderDetailDTO();
            detail.setCarId(id);
            detail.setQty(1);
            CarsDTO carDTO = carSer.findById(id);
            detail.setCarsDTO(carDTO);
            Float amount = carDTO.getPrice() * 1;
            detail.setTotal(amount);
            detail.setPickUpdate(DateTimeUtil.nowDate("MM/dd/yyyy"));
            detail.setDropOffDate(DateTimeUtil.nowDate("MM/dd/yyyy"));
            byte driver = new Byte("0");
            detail.setDriver(driver);
            cart.add(detail);
            JobService serJob = new JobService();
            ArrayList<JobDTO> listJob = serJob.readByAll();
            request.setAttribute("listJob", listJob);
            session.setAttribute("cartCar", cart);
            request.setAttribute("cartCar", cart);
            request.setAttribute("cus", session.getAttribute("cus"));
            request.setAttribute("page", "carbook.page");
            request.setAttribute("pages", "Car Book");
            return mapping.findForward(SUCCESS);
        } else {
            //update cart
            CarOrderDetailDTO detail = new CarOrderDetailDTO();
            detail.setCarId(id);
            if (cart.contains(detail)) {
                CarsDTO carDTO = carSer.findById(id);
                CarOrderDetailDTO detail1 = cart.get(cart.indexOf(detail));
                detail1.setQty(detail1.getQty() + 1);
                detail1.setTotal(carDTO.getPrice() * (detail1.getQty()));
                cart.set(cart.indexOf(detail), detail1);
            } else {
                detail.setQty(1);
                CarsDTO carDTO = carSer.findById(id);
                detail.setCarsDTO(carDTO);
                detail.setTotal(carDTO.getPrice() * 1);
                detail.setPickUpdate(DateTimeUtil.nowDate("MM/dd/yyyy"));
                detail.setDropOffDate(DateTimeUtil.nowDate("MM/dd/yyyy"));
                byte driver = new Byte("0");
                detail.setDriver(driver);
                cart.add(detail);
            }
            JobService serJob = new JobService();
            ArrayList<JobDTO> listJob = serJob.readByAll();
            request.setAttribute("listJob", listJob);
            session.setAttribute("cartCar", cart);
            request.setAttribute("cartCar", cart);
            request.setAttribute("cus", session.getAttribute("cus"));
            request.setAttribute("page", "carbook.page");
            request.setAttribute("pages", "Car Book");
            return mapping.findForward(SUCCESS);
        }


    }

   
    public ActionForward update(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        CarService carSer = new CarService();
        HttpSession session = request.getSession();
        ArrayList<CarOrderDetailDTO> cart = (ArrayList<CarOrderDetailDTO>) session.getAttribute("cartCar");
        for (Iterator<CarOrderDetailDTO> it = cart.iterator(); it.hasNext();) {
            CarOrderDetailDTO carOrderDetailDTOsession = it.next();
            CarOrderDetailDTO carOrderDetailDTO = new CarOrderDetailDTO();
            int carId = carOrderDetailDTOsession.getCarId();
            CarsDTO carDTO = carSer.findById(carId);
            //set new value for cardetailDTO
            carOrderDetailDTO.setCarsDTO(carDTO);
            carOrderDetailDTO.setCarId(carId);
            carOrderDetailDTO.setDriver(new Byte(request.getParameter("driver" + carId)));
            carOrderDetailDTO.setQty(Integer.parseInt(request.getParameter("qty" + carId)));
            carOrderDetailDTO.setPickUpdate(request.getParameter("pickup" + carId));
            carOrderDetailDTO.setDropOffDate(request.getParameter("dropoff" + carId));
            Float total;
            if (carOrderDetailDTOsession.getDriver() == 0) {
                if (request.getParameter("driver" + carId).equals("1")) {
                    total = Float.parseFloat(request.getParameter("total" + carId)) + Float.parseFloat(request.getParameter("total" + carId)) * 20 / 100;
                } else {
                    total = Float.parseFloat(request.getParameter("total" + carId));
                }
            } else {
                if (request.getParameter("driver" + carId).equals("0")) {
                    total = Float.parseFloat(request.getParameter("total" + carId)) - Float.parseFloat(request.getParameter("total" + carId)) * 5 / 30;
                } else {
                    total = Float.parseFloat(request.getParameter("total" + carId));
                }
            }

            carOrderDetailDTO.setTotal(total);
            cart.set(cart.indexOf(carOrderDetailDTOsession), carOrderDetailDTO);
        }
        JobService serJob = new JobService();
        ArrayList<JobDTO> listJob = serJob.readByAll();
        request.setAttribute("listJob", listJob);
        session.setAttribute("cartCar", cart);
        request.setAttribute("page", "carbook.page");
        request.setAttribute("pages", "Car Book");
        return mapping.findForward(SUCCESS);
    }
    //remove

    public ActionForward remove(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        //CarService carSer = new CarService();
        HttpSession session = request.getSession();
        ArrayList<CarOrderDetailDTO> cart = (ArrayList<CarOrderDetailDTO>) session.getAttribute("cartCar");
        CarOrderDetailDTO detail = new CarOrderDetailDTO();
        int id = Integer.parseInt(request.getParameter("carId"));
        detail.setCarId(id);
        cart.remove(cart.indexOf(detail));
        JobService serJob = new JobService();
        ArrayList<JobDTO> listJob = serJob.readByAll();
        if (cart.isEmpty()) {
            request.setAttribute("listJob", listJob);
            session.invalidate();
            //request.setAttribute("cart", cart);
            //request.setAttribute("cus", session.getAttribute("cus"));
            request.setAttribute("id", id);
            request.setAttribute("page", "carbook.page");
            request.setAttribute("pages", "Car Book");
            return mapping.findForward(SUCCESS);
        } else {
            request.setAttribute("listJob", listJob);
            session.setAttribute("cartCar", cart);
            //request.setAttribute("cartCar", cart);
            request.setAttribute("cus", session.getAttribute("cus"));
            request.setAttribute("page", "carbook.page");
            request.setAttribute("pages", "Car Book");
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward Submit(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        CarService carSer = new CarService();
        HttpSession session = request.getSession();
        ArrayList<CarOrderDetailDTO> cart = (ArrayList<CarOrderDetailDTO>) session.getAttribute("cartCar");
        //update lai cart
        float amount = 0;
        for (Iterator<CarOrderDetailDTO> it = cart.iterator(); it.hasNext();) {
            CarOrderDetailDTO carOrderDetailDTOsession = it.next();
            CarOrderDetailDTO carOrderDetailDTO = new CarOrderDetailDTO();
            int carId = carOrderDetailDTOsession.getCarId();
            CarsDTO carDTO = carSer.findById(carId);
            //set new value for cardetailDTO
            carOrderDetailDTO.setCarsDTO(carDTO);
            carOrderDetailDTO.setCarId(carId);
            carOrderDetailDTO.setDriver(new Byte(request.getParameter("driver" + carId)));
            carOrderDetailDTO.setQty(Integer.parseInt(request.getParameter("qty" + carId)));
            carOrderDetailDTO.setPickUpdate(request.getParameter("pickup" + carId));
            carOrderDetailDTO.setDropOffDate(request.getParameter("dropoff" + carId));
            float total;
            if (carOrderDetailDTOsession.getDriver() == 0) {
                if (request.getParameter("driver" + carId).equals("1")) {
                    total = Float.parseFloat(request.getParameter("total" + carId)) + Float.parseFloat(request.getParameter("total" + carId)) * 20 / 100;
                } else {
                    total = Float.parseFloat(request.getParameter("total" + carId));
                }
            } else {
                if (request.getParameter("driver" + carId).equals("0")) {
                    total = Float.parseFloat(request.getParameter("total" + carId)) - Float.parseFloat(request.getParameter("total" + carId)) * 5 / 30;
                } else {
                    total = Float.parseFloat(request.getParameter("total" + carId));
                }
            }
            amount += total;
            carOrderDetailDTO.setTotal(total);
            //thong tin orderdetail
            cart.set(cart.indexOf(carOrderDetailDTOsession), carOrderDetailDTO);
        }
        //set session cart
        session.setAttribute("cartCar", cart);
        //lay thong tin order
        CarOrderDTO carOrderDTO = new CarOrderDTO();
        carOrderDTO.setOrderDate(DateTimeUtil.nowDate("MM/dd/yyyy"));
        carOrderDTO.setAmount(amount);
        //set session carOrder
        session.setAttribute("carOrder", carOrderDTO);
        //thong tin cus
        JobService serJob = new JobService();
        CustomerDTO cusDTO = new CustomerDTO();
        cusDTO.setFullName(request.getParameter("fullName"));
        cusDTO.setEmail(request.getParameter("email"));
        cusDTO.setPhone(request.getParameter("phone"));
        cusDTO.setFax(request.getParameter("fax"));
        cusDTO.setBirthDay(request.getParameter("birth"));
        cusDTO.setCountry(request.getParameter("country"));
        cusDTO.setState(request.getParameter("state"));
        cusDTO.setAddress(request.getParameter("add"));
        JobDTO jobDTO = serJob.findById(Integer.parseInt(request.getParameter("jobId")));
        cusDTO.setJobDTO(jobDTO);
        //set session cus
        session.setAttribute("cus", cusDTO);
        //set request

        request.setAttribute("cartCar", cart);
        request.setAttribute("carOrder", carOrderDTO);
        request.setAttribute("cus", cusDTO);
        request.setAttribute("page", "carbookview.page");
        request.setAttribute("pages", "Car Book");
        return mapping.findForward(SUCCESS);
    }

    public ActionForward Confirm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        //CarService carSer = new CarService();
        HttpSession session = request.getSession();
        ArrayList<CarOrderDetailDTO> cart = (ArrayList<CarOrderDetailDTO>) session.getAttribute("cartCar");
        CarOrderDTO carOrder = (CarOrderDTO) session.getAttribute("carOrder");
        CustomerDTO customer = (CustomerDTO) session.getAttribute("cus");
        customer.setJobId(customer.getJobDTO().getJobId());
        CarOrderService serCarOrder = new CarOrderService();
        CustomerService serCus = new CustomerService();
        CarOrderDetailService serDetail = new CarOrderDetailService();
        boolean flag = true;
        //kiem tra email da ton tai trong csdl 
        //neu chua co thi cho phep them vao
        if (serCus.findByEmail(customer.getEmail()) == null) {
            int cusId = serCus.create(customer);
            if (cusId > 0) {
//            CarOrderDTO orderDTO = new CarOrderDTO();
//            orderDTO.setOrderDate(carOrder.getOrderDate());
//            orderDTO.setAmount(carOrder.getAmount());
                customer.setCustomerId(cusId);
                carOrder.setCustId(cusId);
                int orderId = serCarOrder.create(carOrder);
                if (orderId > 0) {
                    carOrder.setOrderId(orderId);
                    for (Iterator<CarOrderDetailDTO> it = cart.iterator(); it.hasNext();) {
                        CarOrderDetailDTO carOrderDetailDTO = it.next();
                        carOrderDetailDTO.setOderId(orderId);
                        if (!serDetail.create(carOrderDetailDTO)) {
                            flag = false;
                            break;
                        }
                    }
                } else {
                    flag = false;
                }
            } else {
                flag = false;
            }
        } else {
            //hien thi chung nhan la dia chi email dung

            customer = serCus.findByEmail(customer.getEmail());
            int cusId = customer.getCustomerId();
            carOrder.setCustId(cusId);
            int orderId = serCarOrder.create(carOrder);
            if (orderId > 0) {
                carOrder.setOrderId(orderId);
                for (Iterator<CarOrderDetailDTO> it = cart.iterator(); it.hasNext();) {
                    CarOrderDetailDTO carOrderDetailDTO = it.next();
                    carOrderDetailDTO.setOderId(orderId);
                    if (!serDetail.create(carOrderDetailDTO)) {
                        flag = false;
                        break;
                    }
                }
            } else {
                flag = false;
            }
        }

        if (flag) {
            //lay thong tin hien thi lai cho khach hang
            session.invalidate();
            request.setAttribute("cartCar", cart);
            request.setAttribute("carOrder", carOrder);
            request.setAttribute("cus", customer);
            request.setAttribute("page", "carbookinfo.page");
            request.setAttribute("pages", "Car Book");
            return mapping.findForward(SUCCESS);
        } else {
            request.setAttribute("page", "carbookview.page");
            request.setAttribute("pages", "Car Book");
            return mapping.findForward(ERR);
        }
    }

    public ActionForward CancelOrder(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        int num = Integer.parseInt(request.getParameter("num"));
        ArrayList<CarCancelDTO> listcancelDTO = new ArrayList<CarCancelDTO>();
        CarCancelService serCarCancel = new CarCancelService();
        boolean flag = true;
        float money = 0;
        for (int i = 1; i <= num; i++) {
            CarCancelDTO cancelDTO = new CarCancelDTO();
            cancelDTO.setCarOderDetailId(Integer.parseInt(request.getParameter("detailId" + i)));
            cancelDTO.setDiscount(Float.parseFloat(request.getParameter("money" + i)));
            cancelDTO.setDateCancel(DateTimeUtil.nowDate("MM/dd/yyyy"));
            if (!serCarCancel.create(cancelDTO)) {
                flag = false;
            }
            money += cancelDTO.getDiscount();
            listcancelDTO.add(cancelDTO);
        }
        if (flag) {
            request.setAttribute("listCancel", listcancelDTO);
            request.setAttribute("money", money);
            request.setAttribute("page", "carcancelreport.page");
            return mapping.findForward(SUCCESS);
            //thong bao so tien dc nhan lai
        } else {
            //thong bao chua huy dc
            request.setAttribute("listCancel", listcancelDTO);
            request.setAttribute("num", num);
            return mapping.findForward(ERR);
        }
    }
}
